package com.epoint.androidphone.mobileoa.service.mqtt;

import android.content.Context;

import com.epoint.androidphone.R;
import com.ibm.micro.client.mqttv3.MqttClient;
import com.ibm.micro.client.mqttv3.MqttDeliveryToken;
import com.ibm.micro.client.mqttv3.MqttException;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttTopic;

/**
 * @author liyc
 * @time 2013-8-12 上午11:18:24
 * @annotation 
 */
public class MQTTUtil {
	
	public static void p1(Context con,String topicStr,String messageStr)
	{
		MqttClient client = null;
		try {
			// Create a client to communicate with a broker at the specified address
			client = new MqttClient(con.getString(R.string.message_push_server_ip), MqttClient.generateClientId(),null);
			// Connect to the broker
			client.connect();
		} catch (MqttException ex) {
			ex.printStackTrace();
			System.err.println("Could not connect");
		}

		if ((client != null) && client.isConnected()) {
			MqttTopic topic = client.getTopic(topicStr.toString());
			MqttDeliveryToken token = null;
			// Create message and set quality of service to deliver the message once
			MqttMessage message = new MqttMessage(messageStr.toString().getBytes());
			message.setQos(0);

			try {
				// Give the message to the client for publishing.  For QoS 2,
				// this will involve multiple network calls, which will happen 
				// asynchronously after this method has returned.
				token = topic.publish(message);
			}
			catch (MqttException ex) {
				// Client has not accepted the message due to a failure
				// Depending on the exception's reason code, we could always retry
				System.err.println("Failed to send message");
			}

			if (token != null) {
				boolean keepTrying = true;
				do {
					try {
						// Wait for the message delivery to complete
						token.waitForCompletion();
						System.out.println("Message delivery complete");
					}
					catch (MqttException deliveryException) {
						int reasonCode = deliveryException.getReasonCode();
						// TODO: Retry the message, or decide to stop trying
						System.err.println("Message delivery failed");
						if (client.isConnected() == false) {
							try {
								// Re-connect to the server
								client.connect();
							}
							catch (MqttException connectException) {
								// Can't reconnect, so give up.  If and when the 
								// client does reconnect, the message delivery
								// will automatically continue
								keepTrying = false;
							}
						}
					}
				} while (!token.isComplete() && keepTrying);
			}
		}
	}
}
